<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator; 
use Carbon\Carbon;


class AuthController extends Controller
{
    public function register(Request $request)
    {
        // 验证规则
        $validator = Validator::make($request->all(), [
            'mobile'   => 'required|mobile|unique:users',
            'password' => 'required|min:8|confirmed',
            'name'     => 'required|max:20',
            'avatar'   => 'nullable|url'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'errors' => $validator->errors()
            ], 422);
        }

        // 创建用户
        $user = User::create([
            'mobile'   => $request->mobile,
            'password' => bcrypt($request->password),
            'name'     => $request->name,
            'avatar'   => $request->avatar ?? 'https://example.com/default-avatar.png'
        ]);
        $this->generateDefaultBudgets($user);

        // 自动登录并返回 Token
        $token = auth()->login($user);


        $credentials = $request->only('mobile', 'password');
    
        // 调试输出
        logger('Login Attempt:', $credentials);
        logger('User Exists:', ['exists' => User::where('mobile', $credentials['mobile'])->exists()]);

        if (!$token = JWTAuth::attempt($credentials)) {
            logger('JWT Attempt Failed');
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        
        logger('Generated Token:', ['token' => $token]);

        return $this->respondWithToken($token);
    }

    // 为用户生成默认预算
    private function generateDefaultBudgets(User $user)
    {
        // 获取当前年份和月份
        $currentYear = Carbon::now()->year;
        $currentMonth = Carbon::now()->month;
        
        // 为当前月份创建默认预算
        $existingBudget = $user->budgets()->where('year', $currentYear)->where('month', $currentMonth)->first();
        
        if (!$existingBudget) {
            $user->budgets()->create([
                'amount' => 3000.00, // 默认预算金额
                'balance' => 3000.00, // 初始余额等于预算金额
                'year' => $currentYear,
                'month' => $currentMonth
            ]);
        }
    }
    //
    public function login(Request $request)
    {
       

        // 新增密码明文与哈希值对比检查
        $user = User::where('mobile', $request->mobile)->first();
        if ($user && !password_verify($request->password, $user->password)) {
            
            return response()->json(['error' => '密码不匹配',
                'request' => $request->password,
                'user' => $user->password
            ], 401);
        }

        $credentials = $request->validate([
            'mobile' => 'required|mobile',
            'password' => 'required'
        ]);

        if (!$token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => '没有token','credentials'=>$credentials], 401);
        }
        // 检查用户是否为管理员
        $user = auth()->user();
        if ($user->is_admin) {
            auth()->logout();
            return response()->json([
                'message' => '管理员请使用专属登录入口'
            ], 403);
        }

        return $this->respondWithToken($token);
    }

    public function me()
    {
        return response()->json(auth()->user());
    }

    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => config('jwt.ttl') * 60
        ]);
    }

    public function updateAvatar(Request $request)
    {
        // 验证规则
        $validator = Validator::make($request->all(), [
            'avatar' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        // 文件处理
        $avatarPath = $request->file('avatar')->store('avatars', 'public');
        $avatarUrl = asset("storage/$avatarPath");

        // 更新用户头像
        /**
         * @var \App\Models\User $user
         */
        $user = auth()->user();
        $user->avatar = $avatarUrl;
        $user->save();

        return response()->json([
            'message' => '头像更新成功',
            'avatar_url' => $avatarUrl
        ]);
    }
}
